package com.blue.base.security.filters;

import com.blue.base.security.config.SecurityAuthConfig;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录请求细节验证
 *
 * @author liulei
 * @version 1.0
 */
public class UsernamePasswordAuthFilter extends AbstractUsernamePasswordFilter {

    /**
     * @param securityConfig        自定义参数
     * @param authenticationManager 认证管理器
     */
    public UsernamePasswordAuthFilter(SecurityAuthConfig securityConfig, AuthenticationManager authenticationManager) {
        super(securityConfig);
        //1.设置认证管理器
        this.setAuthenticationManager(authenticationManager);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        //2.设置过滤器细节
        if (!request.getMethod().equals(HttpMethod.POST.name())) {
            throw new IllegalArgumentException("登录方法类型错误");
        }
        String username = obtainUsername(request);
        String password = obtainPassword(request);
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            throw new IllegalArgumentException("用户名/密码不能为空");
        }
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
        // 允许认证provider获取filter信息
        this.setDetails(request, authRequest);
        // 3.进入认证环节
        return this.getAuthenticationManager().authenticate(authRequest);
    }

}
